/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.xml.wrda.controller;

import cz.muni.fi.pb138.xml.wrda.core.Wsdl;
import cz.muni.fi.pb138.xml.wrda.servise.WSDLService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Fufi
 */

@Controller
@RequestMapping("/wsdl")
public class WSDLController {
    
    @Autowired
    private WSDLService wsdlService;
    
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addNew() {
        return new ModelAndView("wsdl_add");
    }

    @RequestMapping(value = "/add/", method = RequestMethod.POST)
    public ModelAndView addNew(HttpServletRequest request, @RequestParam CommonsMultipartFile[] fileUpload) {   //dlzka suboru musi byt viac ako 0
        if (fileUpload != null && fileUpload.length > 0) {   // vsechny soubory
            for (CommonsMultipartFile fileToSave : fileUpload) { 
                if (!fileToSave.getOriginalFilename().equals("")) {   // typ suboru je .wsdl 
                    if (StringUtils.endsWith(fileToSave.getOriginalFilename(), ".wsdl")) {
                        try {
                            wsdlService.saveFile(fileToSave.getInputStream(), fileToSave.getOriginalFilename());
                        } catch (IOException ex) {
                            Logger.getLogger(WSDLController.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            }
        }

        return new ModelAndView("redirect:/wsdl/browse");
    }
    
    @RequestMapping(value = "/browse", method = RequestMethod.GET)
    public ModelAndView browse() {

        return new ModelAndView("wsdl_browse", "wsdls", wsdlService.getAllEntriesDistinctNames());
    }
    
    @RequestMapping(value = "/browse", method = RequestMethod.POST)
    public ModelAndView browseByFileName(HttpServletRequest request) {
        String searchTypeSelect = request.getParameter("searchValue");

        return new ModelAndView("wsdl_browse", "wsdls", wsdlService.getAllEntriesDistinctNames());
    }
    
    @RequestMapping(value = "/browse/{fileName}", method = RequestMethod.GET)
    public ModelAndView browseVersions(@PathVariable String fileName) {
        return new ModelAndView("wsdl_versions", "wsdls", wsdlService.getAllEntriesByFileName(fileName + ".wsdl"));
    }

    @RequestMapping(value = "/browse/{fileName}/{timeStamp}")
    public ModelAndView browseWsdlEntry(@PathVariable String fileName, @PathVariable String timeStamp) {
        return new ModelAndView("wsdl_entry", "wsdlEntry", wsdlService.getEntryByFileNameAndTimeStamp(fileName, timeStamp));
    }

    @RequestMapping(value = "/delete/{fileName}")
    public ModelAndView deleteAllVersionsWsdlEntry(@PathVariable String fileName) {
        wsdlService.deleteAllEntryByName(fileName + ".wsdl");
        return new ModelAndView("wsdl_browse", "wsdls", wsdlService.getAllEntriesDistinctNames());
    }

    @RequestMapping(value = "/delete/{fileName}/{timeStamp}")
    public ModelAndView deleteWsdlEntryTimeStamp(@PathVariable String fileName, @PathVariable String timeStamp) {
        wsdlService.deleteEntryByTimeStamp(timeStamp);
        return new ModelAndView("wsdl_browse", "wsdls", wsdlService.getAllEntriesDistinctNames());
    }
    
    @RequestMapping(value = "/download/{fileName}/{timeStamp}")
    public void donwloadWsdlEntryByTimeStamp(@PathVariable String fileName, @PathVariable String timeStamp, HttpServletResponse response) {
        try {
            InputStream inputStream = new ReaderInputStream(wsdlService.getWsdlContentAsInputStream(timeStamp));
            response.setContentType("application/xml");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException ex) {
            Logger.getLogger(WSDLController.class.getName()).log(Level.SEVERE, "Can't start downloading file.", ex);
        }
    }
    
}

